package com.bkkp;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.bkkp.adapter.CategoryAdapter;
import com.bkkp.databinding.BkkpBinding;
import com.common.api.RouterPath;
import com.common.pojo.app.UserInfoPojo;
import com.common.pojo.bkkp.AnalysisPojo;
import com.common.pojo.bkkp.Category;
import com.common.pojo.dto.Result;
import com.common.utils.Constants;
import com.common.utils.ConstantsUrl;
import com.google.android.material.tabs.TabLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;


@Route(path = RouterPath.BKKP_MAIN)
public class BkkpFragment extends Fragment {

    private BkkpBinding bkkpBinding;
    private TabLayout typeTabLayout;
    private EditText amountEditText, remarkEditText;
    private TextView dateTextView, expenseTextView, incomeTextView, balanceTextView;
    private GridView categoryGridView;
    private Button submitButton;
    private CategoryAdapter categoryAdapter;
    private List<Category> categoryList = new ArrayList<>();
    private Calendar selectedDate = Calendar.getInstance();
    private boolean isExpense = true; // 默认是支出
    private UserInfoPojo userInfoPojo;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        bkkpBinding = BkkpBinding.inflate(inflater, container, false);

        // 初始化控件
        initViews();

        // 设置工具栏
        setupToolbar();

        // 设置收支类型切换
        setupTypeTabLayout();

        // 初始化分类数据
        initCategoryData();

        // 设置分类GridView
        setupCategoryGridView();

        // 设置日期选择
        setupDateSelection();

        // 设置提交按钮
        setupSubmitButton();

        //请求远端数据
        reqBkkp();

        // Inflate the layout for this fragment
        return bkkpBinding.getRoot();
    }

    private void initViews() {
        typeTabLayout = bkkpBinding.typeTabLayout;
        amountEditText = bkkpBinding.amountEditText;
        remarkEditText = bkkpBinding.remarkEditText;
        dateTextView = bkkpBinding.dateTextView;
        categoryGridView = bkkpBinding.categoryGridView;
        submitButton = bkkpBinding.submitButton;
        expenseTextView = bkkpBinding.expenseTextView;
        incomeTextView = bkkpBinding.incomeTextView;
        balanceTextView = bkkpBinding.balanceTextView;
        userInfoPojo = JSONObject.parseObject(Constants.userInfo, UserInfoPojo.class);
        // 显示当前日期
        updateDateDisplay();
    }

    private void setupToolbar() {
        Toolbar toolbar = bkkpBinding.toolbar;
        AppCompatActivity activity = (AppCompatActivity) requireActivity();
        activity.setSupportActionBar(toolbar);
        activity.getSupportActionBar().setDisplayShowTitleEnabled(false);
    }

    private void setupTypeTabLayout() {
        typeTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                isExpense = tab.getPosition() == 0;
                initCategoryData(); // 切换收支类型时更新分类
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    private void initCategoryData() {
        categoryList.clear();
        if (isExpense) {
            // 支出分类
            categoryList.add(new Category("餐饮", R.drawable.ic_baseline_restaurant_24, true));
            categoryList.add(new Category("购物", R.drawable.ic_baseline_shopping_cart_24, false));
            categoryList.add(new Category("交通", R.drawable.ic_baseline_directions_bus_24, false));
            categoryList.add(new Category("生活", R.drawable.ic_life, false));
            categoryList.add(new Category("娱乐", R.drawable.ic_baseline_movie_24, false));
            categoryList.add(new Category("医疗", R.drawable.ic_baseline_local_hospital_24, false));
            categoryList.add(new Category("教育", R.drawable.ic_baseline_school_24, false));
            categoryList.add(new Category("通讯", R.drawable.ic_baseline_message_24, false));
            categoryList.add(new Category("社交", R.drawable.ic_social, false));
            categoryList.add(new Category("其他", R.drawable.ic_other, false));
        } else {
            // 收入分类
            categoryList.add(new Category("工资", R.drawable.ic_baseline_work_24, true));
            categoryList.add(new Category("奖金", R.drawable.ic_baseline_card_giftcard_24, false));
            categoryList.add(new Category("投资", R.drawable.ic_baseline_insert_invitation_24, false));
            categoryList.add(new Category("兼职", R.drawable.ic_parttime, false));
            categoryList.add(new Category("理财", R.drawable.ic_finance, false));
            categoryList.add(new Category("红包", R.drawable.ic_red_envelope, false));
            categoryList.add(new Category("退税", R.drawable.ic_baseline_print_24, false));
            categoryList.add(new Category("中奖", R.drawable.ic_baseline_insert_invitation_24, false));
            categoryList.add(new Category("其他", R.drawable.ic_other, false));
        }

        if (categoryAdapter != null) {
            categoryAdapter.notifyDataSetChanged();
        }
    }

    private void setupCategoryGridView() {
        categoryAdapter = new CategoryAdapter(getContext(), categoryList);
        categoryGridView.setAdapter(categoryAdapter);

        categoryGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 重置所有分类的选中状态
                for (Category category : categoryList) {
                    category.setSelected(false);
                }

                // 设置当前选中的分类
                categoryList.get(position).setSelected(true);
                categoryAdapter.notifyDataSetChanged();
            }
        });
    }

    private void setupDateSelection() {
        dateTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(
                        getContext(),
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                                selectedDate.set(Calendar.YEAR, year);
                                selectedDate.set(Calendar.MONTH, month);
                                selectedDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                updateDateDisplay();
                            }
                        },
                        selectedDate.get(Calendar.YEAR),
                        selectedDate.get(Calendar.MONTH),
                        selectedDate.get(Calendar.DAY_OF_MONTH)
                );
                datePickerDialog.show();
            }
        });
    }

    private void updateDateDisplay() {
        Date date = selectedDate.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        dateTextView.setText(sdf.format(date));
    }

    private void setupSubmitButton() {
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String amountStr = amountEditText.getText().toString().trim();
                if (amountStr.isEmpty()) {
                    showToast("请输入金额");
                    return;
                }

                double amount = Double.parseDouble(amountStr);
                if (amount <= 0) {
                    showToast("金额必须大于0");
                    return;
                }

                // 获取选中的分类
                Category selectedCategory = null;
                for (Category category : categoryList) {
                    if (category.isSelected()) {
                        selectedCategory = category;
                        break;
                    }
                }

                if (selectedCategory == null) {
                    showToast("请选择分类");
                    return;
                }

                String remark = remarkEditText.getText().toString().trim();

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                String date = sdf.format(new Date());

                // 这里处理记账逻辑，例如保存到数据库
                saveAccountingRecord(amount, selectedCategory.getName(), remark, date, isExpense);
            }
        });
    }

    private void saveAccountingRecord(double amount, String category, String remark, String date, boolean isExpense) {
        String url = ConstantsUrl.bkkpUrl;//消费
        Map<String, String> map = new HashMap<>();
        map.put("userId", userInfoPojo.getId().toString());
        map.put("date", date);
        map.put("category", category);
        map.put("amount", String.valueOf(amount));
        map.put("remark", remark);
        if (isExpense) {
            //支出
            map.put("type", "2");
        } else {
            //收入
            map.put("type", "1");
        }
        OkHttpUtils
                .post()
                .url(url)
                .params(map)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (e instanceof java.net.SocketTimeoutException) {
                            showToast("网络连接超时，请检查网络设置");
                        } else if (e instanceof java.io.IOException) {
                            showToast("网络请求失败，请检查网络连接");
                        } else {
                            showToast("网络请求出现未知错误");
                        }
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        // 处理响应
                        Log.d("TAG", "Response: " + response);
                        Result result = null;
                        try {
                            result = JSONObject.parseObject(response, Result.class);
                        } catch (Exception e) {
                        }
                        if (result == null) {
                            result = Result.fail("请求返回失败");
                        }
                        if (result.getSuccess()) {
                            reqBkkp();
                            showToast("记账成功");
                            if (isAdded() && getView() != null) { // 双重校验（可选）
                                amountEditText.setText("");
                                remarkEditText.setText("");
                            }
                        } else {
                            showToast(result.getMessage());
                        }
                    }
                });
    }

    private void updateStatistics(AnalysisPojo analysisPojo) {
        if (isAdded() && getView() != null) { // 双重校验（可选）
            // 这里更新统计数据，从数据库获取今日收支情况
            // 示例数据，实际应从数据库查询
            expenseTextView.setText(String.format("¥%.2f", analysisPojo.getNsume()));
            incomeTextView.setText(String.format("¥%.2f", analysisPojo.getIncome()));
            balanceTextView.setText(String.format("¥%.2f", analysisPojo.getSurplus()));

            balanceTextView.setTextColor(analysisPojo.getSurplus() >= 0
                    ? Color.parseColor("#2196F3")
                    : Color.parseColor("#E12F2F"));
        }
    }


    //请求远端数据
    private void reqBkkp() {
        OkHttpUtils.get()
                .url(ConstantsUrl.dayAnlysisUrl)
                .addParams("userId", userInfoPojo.getId().toString())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (e instanceof java.net.SocketTimeoutException) {
                    showToast("网络连接超时，请检查网络设置");
                } else if (e instanceof java.io.IOException) {
                    showToast("网络请求失败，请检查网络连接");
                } else {
                    showToast("网络请求出现未知错误");
                }
            }

            @Override
            public void onResponse(String response, int id) {
                Result result = null;
                try {
                    result = JSONObject.parseObject(response, Result.class);
                } catch (Exception e) {
                }
                if (result == null) {
                    result = Result.fail("请求返回失败");
                }
                if (result.getSuccess()) {
                    AnalysisPojo analysisPojo = JSONObject.parseObject(result.getData().toString(), AnalysisPojo.class);
                    updateStatistics(analysisPojo);
                } else {
                    showToast(result.getMessage());
                }
            }
        });
    }

    private void showToast(String content) {
        requireActivity().runOnUiThread(() -> {
            if (isAdded() && getView() != null) { // 双重校验（可选）
                Toast.makeText(requireContext(), content, Toast.LENGTH_SHORT).show();
            }
        });
    }
}